package com.example.wuyeguanli.activity;

import android.view.View;
import androidx.test.espresso.UiController;
import androidx.test.espresso.ViewAction;
import androidx.test.espresso.action.GeneralClickAction;
import androidx.test.espresso.action.Press;
import androidx.test.espresso.action.Tap;
import org.hamcrest.Matcher;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayingAtLeast;

public class CustomViewActions {

    /**
     * 一个更强大的点击动作，它会先尝试滚动到视图，
     * 然后即使视图只显示了1%也执行点击。
     * 这可以解决标准click()因视图被部分遮挡而失败的问题。
     * @return a ViewAction
     */
    public static ViewAction forceClick() {
        // 先滚动到视图
        androidx.test.espresso.action.ScrollToAction scroller = new androidx.test.espresso.action.ScrollToAction();
        // 然后使用一个低可见度要求的点击动作
        GeneralClickAction clicker = new GeneralClickAction(
                Tap.SINGLE,
                view -> {
                    // 点击视图中心
                    final float[] coordinates = new float[2];
                    coordinates[0] = view.getWidth() / 2.0f;
                    coordinates[1] = view.getHeight() / 2.0f;
                    return coordinates;
                },
                Press.FINGER,
                0, // 不关心输入设备
                0  // 不关心按钮状态
        );

        // 将两个动作组合起来
        return new ViewAction() {
            @Override
            public Matcher<View> getConstraints() {
                // 将可见性要求降低到1%
                return isDisplayingAtLeast(1);
            }

            @Override
            public String getDescription() {
                return "force click";
            }

            @Override
            public void perform(UiController uiController, View view) {
                // 先尝试滚动
                try {
                    scroller.perform(uiController, view);
                } catch (Exception e) {
                    // 滚动失败也没关系，继续尝试点击
                }
                // 然后执行点击
                clicker.perform(uiController, view);
            }
        };
    }
}